package cn.ekuma.pos.pda.inventory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import com.dzh.operateimage.ImageTools;
import com.openbravo.bean.Product;
import com.openbravo.bean.pda.ProductByteImage;
import com.openbravo.data.basic.BasicException;
import android.graphics.PorterDuff.Mode;
import cn.ekuma.data.dao.I_DataLogic;
import cn.ekuma.epos.datalogic.DataLogicPDA;
import cn.ekuma.epos.datalogic.I_DataLogicPDA;
import cn.ekuma.pos.android.customer.R;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.Shader.TileMode;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import cn.com.gallery.GalleryFlow;

public class ProductImageActivate extends Activity implements OnItemSelectedListener, ViewFactory  {

	public static final String SELECTED_BEAN="selected_bean";
	
	public static final int MSG_SUCCESS = 0;
    public static final int MSG_FAILURE = 1;
    public static final int MSG_SAVED = 2;
    
	private Gallery gImage;

	private ArrayList<ProductByteImage> images;
	
    public static final String IMAGE_UNSPECIFIED = "image/*";  

	private Product obj;

	private ImageAdapter imageAdapter; 
	
	private ImageSwitcher mSwitcher;

	
	
	 public static final int NONE = 0;  
	    public static final int PHOTOHRAPH = 1;// 拍照   
	    public static final int PHOTOZOOM = 2; // 缩放   
	    public static final int PHOTORESOULT = 3;// 结果   

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
  	    //实现照相相片翻转
		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		

		// 设置全屏模式
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
			//	WindowManager.LayoutParams.FLAG_FULLSCREEN); 
					
		// 去除标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		
		setContentView(R.layout.guide);
	
		mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
		mSwitcher.setFactory(this);

		mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left));

		mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right));

		/**
		 * xml获取Gallery
		 */
		gImage = (Gallery) findViewById(R.id.mygallery);
		
		
		imageAdapter=new ImageAdapter(this);
		gImage.setAdapter(imageAdapter);
		
		gImage.setOnItemSelectedListener(this);

		/**
		 * 点击事件监听器
		 */
		gImage.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				
			}
		});
		
		Bundle mBundle=getIntent().getExtras();
		obj=(Product) mBundle.getSerializable(SELECTED_BEAN);
		registerForContextMenu(gImage);

		initData();
	}
	

	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		ProductByteImage productImage =images.get(position);
		mSwitcher.setImageDrawable(ImageTools.bitmapToDrawableByBD(ImageTools.bytesToBimap(productImage.getM_ImageDatas())));	
	}


	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub

	}
	
	public View makeView() {

		ImageView i = new ImageView(this);

		i.setBackgroundColor(0xFF000000);

		i.setScaleType(ImageView.ScaleType.FIT_XY);

		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return i;
	}
	
	
	protected void initData() {
			final ProgressDialog dialog = ProgressDialog.show(this, "", 
			        "查旬中，请稍等 …", true, true);
			new Thread(){
				@SuppressWarnings({ "unchecked"})
				
				public void run(){
					I_DataLogic dlPDA=DataLogicPDA.getDataLogic();
				try{
					ArrayList<ProductByteImage> images=(ArrayList<ProductByteImage>) dlPDA.listWithParentClassAndKey(ProductByteImage.class.getName(),Product.class.getName(),obj.getID());
					mHandler.obtainMessage(MSG_SUCCESS,images).sendToTarget();
				} catch (BasicException e) {
					mHandler.obtainMessage(MSG_FAILURE).sendToTarget();
				}
				dialog.dismiss(); 
			}
			}.start();
	}

	
	public Handler mHandler = new Handler() {  
        public void handleMessage (Message msg) {//此方法在ui线程运行   
            switch(msg.what) {  
            case MSG_SUCCESS:
            	images=(ArrayList<ProductByteImage>) msg.obj;
            	if(images==null)
            		images=new ArrayList();
            	else
            		imageAdapter.notifyDataSetChanged();
                break;  
            case MSG_FAILURE:  
                Toast.makeText(getApplication(), "执行出错了", Toast.LENGTH_LONG).show();  
                break;
            case MSG_SAVED:
            	ProductByteImage productImage=(ProductByteImage) msg.obj;
            	images.add(productImage);
	            imageAdapter.notifyDataSetChanged();	        
        }  
    }
 };
	
 public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    menu.add(Menu.NONE, 0, Menu.NONE, "拍照");
		menu.add(Menu.NONE, 1, Menu.NONE, "从相册选取");
	    return true;
 }
 
 public boolean onOptionsItemSelected(MenuItem item) {
	  switch (item.getItemId()){
		case 0:
			 Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
             intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));  
             startActivityForResult(intent1, PHOTOHRAPH); 
             break;
		 case 1:
	    	   Intent intent = new Intent(Intent.ACTION_PICK, null);  
	           intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);  
	           startActivityForResult(intent, PHOTOZOOM);  
			break;
	  }
	  return true;
 }

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
		menu.add(Menu.NONE, 0, position, "删除当前");
		menu.add(Menu.NONE, 1, position, "编辑");
		menu.add(Menu.NONE, 2, position, "设为商品主图");
	}
	
	public boolean onContextItemSelected(MenuItem item) {
		int position = item.getItemId();
		final int order = item.getOrder();
		switch (position) {
		case 0:
			
			break;
		case 1:
			
			break;
		case 2:
			
			final ProgressDialog dialog = ProgressDialog.show(this, "", 
			        "保存中，请稍等 …", true, true);
			new Thread(){
				@SuppressWarnings({ "unchecked"})
				
				public void run(){
					I_DataLogicPDA dlPDA=DataLogicPDA.getDataLogicPDA();
				try{
					ProductByteImage productImage = images.get(order);
					dlPDA.saveMainProductImage(productImage.getProductId(),productImage.getM_ImageDatas());
					//mHandler.obtainMessage(MSG_SAVED,productImage).sendToTarget();
				} catch (BasicException e) {
					mHandler.obtainMessage(MSG_FAILURE).sendToTarget();
				}
				dialog.dismiss(); 
			}
			}.start();
			
		}
		return true;
	}
	

public class ImageAdapter extends BaseAdapter {

	private int mGalleryItemBackground;
	private Context mContext;

	public ImageAdapter(Context c) {
		mContext = c;

		TypedArray typedArray = mContext.obtainStyledAttributes(R.styleable.Gallery);

		mGalleryItemBackground = typedArray.getResourceId(
				R.styleable.Gallery_android_galleryItemBackground, 0);
		typedArray.recycle();
	}
	
	public ImageView createReflectedImages(ProductByteImage productImage) {

		final int reflectionGap = 4;

		Bitmap originalImage = ImageTools.bytesToBimap(productImage.getM_ImageDatas());
		
		int width = originalImage.getWidth();
		int height = originalImage.getHeight();

		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
				height / 2, width, height / 2, matrix, false);

		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);

		/**
		 * 创建一个绘有bitmapWithReflection的画布，画布质量和bitmapWithReflection质量相同
		 * 也就相当于把bitmapWithReflection作为画布使用
		 * 该画布高度为 原图 + 间隔 + 倒影
		 */
		Canvas canvas = new Canvas(bitmapWithReflection);

		/**
		 * 在画布左上角（0,0）绘制原始图
		 */
		canvas.drawBitmap(originalImage, 0, 0, null);

		Paint deafaultPaint = new Paint();

		canvas.drawRect(0, height, width, height + reflectionGap,
				deafaultPaint);

		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

		Paint paint = new Paint();

		LinearGradient shader = new LinearGradient(0, originalImage
				.getHeight(), 0, bitmapWithReflection.getHeight()
				+ reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);

		paint.setShader(shader);

		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

			/**
			 * 在倒影图上用带阴影的画笔绘制矩形
			 */
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);

		ImageView imageView = new ImageView(mContext);
			
			/**
			 * BitmapDrawable bd = new BitmapDrawable(bitmapWithReflection);
			 * bd.setAntiAlias=true;
			 * imageView.setImageDrawable(bd);
			 * 替代下面：
			 * imageView.setImageBitmap(bitmapWithReflection);
			 * 可实现消除锯齿的效果
			 */
		imageView.setImageBitmap(bitmapWithReflection);
		imageView.setLayoutParams(new GalleryFlow.LayoutParams(180, 240));
		imageView.setBackgroundResource(mGalleryItemBackground);
			
			/**
			 * 设置图像缩放模式以适应ImageView大小。ScaleType.MATRIX：绘制时使用图像变换矩阵缩放。
			 * 
			 * 注意：如果执行此行代码，则原始图盛满整个ImageView，无倒影效果
			 */
		//imageView.setScaleType(ScaleType.MATRIX);
		return imageView;
	}
	
	/** 获得图片数量*/
	public int getCount() {
		return images==null?0:images.size();
	}
	

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		return createReflectedImages(images.get(position));
	}
//	public float getScale(boolean focused, int offset) {
//		/* Formula: 1 / (2 ^ offset) */
//		return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
//	}
}
	
	
	
	@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (resultCode == NONE)  
            return;  
        // 拍照   
        if (requestCode == PHOTOHRAPH) {  
            //设置文件保存路径这里放在跟目录下   
            File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");  
            startPhotoZoom(Uri.fromFile(picture));  
        }  
          
        if (data == null)  
            return;  
          
        // 读取相册缩放图片   
        if (requestCode == PHOTOZOOM) {  
            startPhotoZoom(data.getData());  
        }  
        // 处理结果   
        if (requestCode == PHOTORESOULT) {  
            Bundle extras = data.getExtras();  
            if (extras != null) {  
            	File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");  
            	final ProductByteImage productImage=new ProductByteImage();
                productImage.setProductId(this.obj.getID());
                productImage.setM_Name(String.valueOf(new Date()));
            	try {
					FileInputStream  inStream=new FileInputStream(picture);
					int length = inStream.available();       
					   byte [] buffer = new byte[length];        
					   inStream.read(buffer);         
					   productImage.setM_ImageDatas(buffer);
					   inStream.close();      
					   //依bbi.txt的编码类型选择合适的编码，如果不调整会乱码         
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					return;
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
            	
            	final ProgressDialog dialog = ProgressDialog.show(this, "", 
    			        "保存中，请稍等 …", true, true);
    			new Thread(){
    				@SuppressWarnings({ "unchecked"})
    				
    				public void run(){
    					I_DataLogicPDA dlPDA=DataLogicPDA.getDataLogicPDA();
    				try{
    					dlPDA.insert(productImage);
    					mHandler.obtainMessage(MSG_SAVED,productImage).sendToTarget();
    				} catch (BasicException e) {
    					mHandler.obtainMessage(MSG_FAILURE).sendToTarget();
    				}
    				dialog.dismiss(); 
    			}
    			}.start();
            	
                //Bitmap photo = extras.getParcelable("data");  
                //ByteArrayOutputStream stream = new ByteArrayOutputStream();  
                //photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)压缩文件   
                //imageView.setImageBitmap(photo);  
            }  
        }  
        super.onActivityResult(requestCode, resultCode, data);  
    }  
  
    public void startPhotoZoom(Uri uri) {  
        Intent intent = new Intent("com.android.camera.action.CROP");  
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);  
        intent.putExtra("crop", "true");  
        // aspectX aspectY 是宽高的比例   
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
        // outputX outputY 是裁剪图片宽高   
        intent.putExtra("outputX", 600);  
        intent.putExtra("outputY", 400);  
        //intent.putExtra("return-data", true);  
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
        startActivityForResult(intent, PHOTORESOULT);  
    }  

	
}
